package com.qyoung.dao.impl;

import com.qyoung.dao.BaseDao;
import com.qyoung.dao.UserDao;
import com.qyoung.pojo.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public boolean login(String username, String password) {
        String sql = "select * from user where username=? and password=?";
        List<String> param = new ArrayList<>();
        param.add(username);
        param.add(password);
        ResultSet rs = query(sql, param);
        try {
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<User> findAll() {
        String sql = "select * from user";
        ResultSet rs = query(sql, null);
        List<User> users = new ArrayList<>();
        try {
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setTelephone(rs.getString("telephone"));

                users.add(user);
            }
            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public boolean findByName(String name) {
        String sql = "select * from user where username=?";
        List param = new ArrayList();
        param.add(name);
        ResultSet rs = query(sql, param);
        try {
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public User findById(Integer id) {
        String sql = "select * from user where id=?";
        List<Integer> param = new ArrayList<>();
        param.add(id);
        ResultSet rs = query(sql, param);
        User user = new User();
        try {
            while (rs.next()) {
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
